<script setup lang="ts">
import getUserAgent from 'gdt-jsapi/getUserAgent';
import dd from 'gdt-jsapi';
import { onMounted } from 'vue';
import { state, historyState, scheduleTimeState, filter } from './state';
import dayjs from 'dayjs';
import {
  navigateTo,
  showModal,
  showLoading,
  hideLoading,
  navigateBack,
  showToast,
  reLaunch,
} from '@tarojs/taro';
import {
  APP_SCHEDULE_MODEL_QUERY,
  APP_SCHEDULE_CONTENT_QUERY,
  APP_SCHEDULE_TIME_LIST_BY_USER_QUERY,
  INSERT_APP_SCHEDULE_RECORD,
  NOTE_APP_SCHEDULE_RECORD,
} from '/@/api/modules/base/schedule-app';
import { LOGIN_APP } from '/@/api/modules/base/app-sys-user';
import { Right as AppNutIconRight } from '@nutui/icons-vue-taro';

/**
 * @function 上传文件
 * @param imgList
 */
function uploadImageChange(imgList: { key: string; src: string }[]) {
  historyState.content!.file = imgList.map((i) => {
    return {
      fileType: 1,
      fileUrl: i.src,
      fileName: i.src.split('/').reverse()[0],
    };
  }) as ScheduleApp.Dto[];
}

onMounted(() => {
  showLoading();
  LOGIN_APP().then((res) => {
    state.appUserId = res.sysUserDto.id || '';
    filter.scheduleTimeList = [];
    queryAppScheduleModel();
  });
  inDDEnvironment();
});

function inDDEnvironment() {
  try {
    getUserAgent().then(() => {
      ddBack();
    });
  } catch (error) {
    console.log(error);
  }
}

// 判断是否为安卓
function isAndroid() {
  const u = navigator.userAgent;
  if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) {
    if (window.ShowFitness !== undefined) return true;
  }
  return false;
}

/**
 *
 */
function ddBack() {
  dd.ready(() => {
    // 设置左上角返回事件可控
    dd.setNavLeftText({
      control: true,
      message: '返回',
      text: '返回',
      android: isAndroid() ? true : false,
    }).then(() => {
      const off = dd.on('back', function (e) {
        e.preventDefault();
        showModal({
          title: '保存草稿',
          content: '您确定要保存草稿吗?',
          success: function (response) {
            if (response.confirm) {
              off();
              saveDraft();
            } else if (response.cancel) {
              off();
              dd.goBack();
            }
          },
        });
      });
    });
  });
}

/**
 * @function 发起交接——获取当前登录用户的交接页面
 */
function queryAppScheduleModel() {
  APP_SCHEDULE_MODEL_QUERY({
    userId: state.appUserId,
  }).then((res) => {
    if (res.check === 2) {
      showModal({
        title: '历史草稿',
        content: '您确定要采用上次历史草稿吗？',
        success: function (response) {
          if (response.confirm) {
            historyState.content = res.history;
          } else if (response.cancel) {
            historyState.content = res.content;
          }
        },
      });
    } else {
      historyState.content = res.content;
    }
    queryAppScheduleTimeListByUser(historyState.content?.modelId);
  });
}

/**
 *  发起交接——获取读数
 */
function queryAppScheduleContent(content?: ScheduleApp.AppScheduleRecord) {
  const ids = (content?.record?.map((item) => item.contentId) as string[]) || ([] as string[]);
  APP_SCHEDULE_CONTENT_QUERY({ ids: ids }).then((res) => {
    content?.record?.forEach((item) => {
      if (!res.content) {
        return;
      }
      item.contentValue = res.content[item.contentId!];
    });
  });
}

/**
 * 交接班时列表
 * @param modelId 模版id
 */
function queryAppScheduleTimeListByUser(modelId?: string) {
  APP_SCHEDULE_TIME_LIST_BY_USER_QUERY({ userId: state.appUserId, modelId }).then((res) => {
    scheduleTimeState.content = res.content;
    filter.scheduleTimeList = [];
    res.content?.forEach((item, index) => {
      filter.scheduleTimeList.push({
        text: item.scheduleName,
        value: index.toString(),
      });
    });
  });
}

/**
 * 交接班时确认回调
 * @param selectedValue 选中项的value集合
 */
function scheduleTimeConfirm({ selectedValue }) {
  console.log(selectedValue[0]);
  const index = Number(selectedValue[0]);
  if (!historyState.content || !scheduleTimeState.content || !scheduleTimeState.content.length) {
    return;
  }
  historyState.content.scheduleId = scheduleTimeState.content[index].scheduleId;
  historyState.content.scheduleName = scheduleTimeState.content[index].scheduleName;
  historyState.content.scheduleTimeId = scheduleTimeState.content[index].scheduleTimeId;
  historyState.content.scheduleTimeName = scheduleTimeState.content[index].scheduleTimeName;
  historyState.content.floatTimeBegin = scheduleTimeState.content[index].floatTimeBegin;
  historyState.content.floatTimeEnd = scheduleTimeState.content[index].floatTimeEnd;
  filter.filterTypeVisible = false;
}
/**
 * 新增记录
 */
function submit() {
  showLoading();
  INSERT_APP_SCHEDULE_RECORD({ content: historyState.content }).then((res) => {
    hideLoading();
    if (res.comResp?.code === 100) {
      navigateTo({
        url: `/pages/swap/start-success/index?id=${res.id}`,
      });
    }
  });
}
/**
 * 返回按钮
 */
function back() {
  showModal({
    title: '保存草稿',
    content: '您确定要保存草稿吗?',
    success: function (response) {
      if (response.confirm) {
        saveDraft();
      } else if (response.cancel) {
        navigateBack();
      }
    },
  });
}

/**
 * 保存草稿
 */
function saveDraft() {
  showLoading();
  NOTE_APP_SCHEDULE_RECORD({ content: historyState.content }).then((res) => {
    if (res.comResp?.code === 100) {
      showToast({ title: '保存草稿成功', icon: 'success' });
      navigateBack();
    }
  });
}
</script>

<template>
  <view class="swap-start app-page--1">
    <app-navbar title="交接班" :hookBack="true" @handleBack="back()" />
    <nut-tabs
      model-value="start"
      @click="
        ({ paneKey }) => {
          if (paneKey === 'record') {
            reLaunch({ url: '/pages/swap/list/index' });
          }
        }
      "
    >
      <nut-tab-pane title="发起交接" pane-key="start" />
      <nut-tab-pane title="交接记录" pane-key="record" />
    </nut-tabs>
    <scroll-view
      class="scroll-view-height__start app-page__wrapper"
      :scroll-y="true"
      :lower-threshold="100"
    >
      <view class="swap-start__wrapper">
        <nut-cell-group>
          <nut-cell title="所属部门" :desc="historyState.content?.organName || '_'" />
          <nut-cell
            title="交接班时"
            :desc="historyState.content?.scheduleName || '_'"
            @click="filter.filterTypeVisible = !filter.filterTypeVisible"
          >
            <template v-slot:link>
              <app-nut-icon-right />
            </template>
          </nut-cell>
          <nut-cell
            title="交接时间"
            :desc="
              dayjs(historyState.content?.floatTimeBegin).format('YYYY-MM-DD HH:mm') +
              '-' +
              dayjs(historyState.content?.floatTimeEnd).format('HH:mm')
            "
          />
        </nut-cell-group>
        <nut-cell-group>
          <nut-cell>
            <template v-slot:title>
              <text class="swap-start__title">交接内容</text>
            </template>
          </nut-cell>
          <nut-cell title="1.设备运行方式及变更情况:" />
          <nut-cell>
            <template v-slot:title>
              <view v-for="item in historyState.content?.state" :key="item.id">
                <text>{{ item.contentName }}</text>
                <nut-input
                  class="swap-start__input"
                  placeholder="请输入"
                  type="text"
                  v-model="item.contentValue"
                />
              </view>
            </template>
          </nut-cell>
          <nut-cell title="2.读数记录:">
            <template #link>
              <nut-button
                type="info"
                size="mini"
                @click="queryAppScheduleContent(historyState.content)"
                >获取读数</nut-button
              >
            </template>
          </nut-cell>
          <nut-cell
            class="swap-start__nut-cell-none-border"
            v-for="item in historyState.content?.record"
            :key="item.id"
          >
            <template v-slot:title>
              <text>{{ item.contentName }}</text>
            </template>
            <template #link>
              <nut-input
                placeholder="请输入"
                class="swap-start__input-small"
                type="text"
                v-model="item.contentValue"
              />
            </template>
          </nut-cell>
          <nut-cell title="3.确认事项:" />
          <nut-cell
            v-for="item in historyState.content?.event"
            :key="item.id"
            class="swap-start__nut-cell-none-border"
          >
            <template v-slot:title>
              <text>{{ item.contentName }}</text>
            </template>
            <template #link>
              <nut-radio-group v-model="item.contentValue" direction="horizontal">
                <nut-radio label="1">是</nut-radio>
                <nut-radio label="2">否</nut-radio>
              </nut-radio-group>
            </template>
          </nut-cell>
        </nut-cell-group>
        <nut-cell-group>
          <nut-cell>
            <template #title>
              <text class="swap-start__title">提醒事项</text>
              <nut-textarea
                placeholder="请输入提醒事项"
                rows="8"
                limit-show
                text-align="left"
                max-length="200"
                v-model="(historyState.content || {}).remind"
              />
            </template>
          </nut-cell>
        </nut-cell-group>
        <nut-cell-group>
          <nut-cell>
            <template v-slot:title>
              <text class="swap-start__title">关联事项</text>
            </template>
          </nut-cell>
          <nut-cell>
            <template v-slot:title>
              <text>维修工单</text>
              <view
                v-if="
                  historyState.content?.workOrderContent &&
                  historyState.content?.workOrderContent.length > 0
                "
                v-for="item in historyState.content?.workOrderContent"
                :key="item.clickId"
              >
                <text class="swap-start__link">{{ item.clickName }}</text>
              </view>
              <view v-else>
                <text>无</text>
              </view>
            </template>
          </nut-cell>
          <nut-cell>
            <template v-slot:title>
              <text>报警记录</text>
              <view
                v-if="
                  historyState.content?.alarmContent &&
                  historyState.content?.alarmContent.length > 0
                "
                v-for="item in historyState.content?.alarmContent"
                :key="item.clickId"
              >
                <text class="swap-start__link">{{ item.clickName }}</text>
              </view>
              <view>
                <text>无</text>
              </view>
            </template>
          </nut-cell>
        </nut-cell-group>
        <nut-cell-group>
          <nut-cell>
            <template v-slot:title>
              <text class="swap-start__title">上传图片</text>
              <view>
                <app-upload-image @on-change="uploadImageChange" module="schedule" :max="3" />
              </view>
            </template>
          </nut-cell>
        </nut-cell-group>
      </view>
    </scroll-view>
    <view class="swap-start__footer">
      <view class="swap-start__footer--btn">
        <nut-button block type="info" @click="submit"> 提交</nut-button>
      </view>
    </view>
    <nut-popup position="bottom" v-model:visible="filter.filterTypeVisible">
      <nut-picker
        :columns="filter.scheduleTimeList"
        title="请选择交接班时"
        @confirm="scheduleTimeConfirm"
        @cancel="filter.filterTypeVisible = false"
      />
    </nut-popup>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
